package HomeWork5;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DruidUtils {
    private static DataSource dataSource;
    private static Connection connection;
    static{
        Properties properties = new Properties();
        try {
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            System.out.println(properties);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnect() throws SQLException {
        connection= dataSource.getConnection();
        return connection;

    }
    public static void close(Connection connection, PreparedStatement preparedStatement){
        if (connection==null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null==preparedStatement){
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Connection con, PreparedStatement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null)
        {
            try
            {
                resultSet.close();
                statement.close();
                con.close(); }
            catch
            (SQLException e)
            { e.printStackTrace();
            }
        }
    }


}
